package reliability.ui;

import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

public class IntegerField
    extends JFormattedTextField
{

    public IntegerField(Object value, int columns)
    {
        super();
        NumberFormat format = new DecimalFormat();
        format.setGroupingUsed(false);
        setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(format)));
        setValue(value);
        setColumns(columns);
    }

    protected void processKeyEvent(KeyEvent e)
    {
        char keyChar = e.getKeyChar();
        if (e.getID() == KeyEvent.KEY_TYPED)
        {
            if (!Character.isDigit(keyChar) || (getText().length() > 8))
            {
                return;
            }
        }
        super.processKeyEvent(e);
    }

    protected void processFocusEvent(FocusEvent e)
    {
        int eventId = e.getID();
        if (eventId == FocusEvent.FOCUS_LOST)
        {
            try
            {
                commitEdit();
            }
            catch (ParseException parseException)
            {
                //do nothing
            }
        }
        super.processFocusEvent(e);
        setCaretPosition(getText().length());
    }

}
